package android.slc.appbase.repository.local;

import com.blankj.utilcode.util.SPUtils;

import java.util.Set;

public class DbSp implements DataPersistence<DbSp> {
    private final String spName;
    private final SPUtils spUtils;

    public DbSp(String spName) {
        this.spName = spName;
        spUtils = SPUtils.getInstance(spName);
    }

    @Override
    public int getInt(String key, int defValue, boolean autoSaveDefValue) {
        autoSaveDefValue(key, defValue, autoSaveDefValue);
        return spUtils.getInt(key, defValue);
    }

    @Override
    public long getLong(String key, long defValue, boolean autoSaveDefValue) {
        autoSaveDefValue(key, defValue, autoSaveDefValue);
        return spUtils.getLong(key, defValue);
    }

    @Override
    public float getFloat(String key, float defValue, boolean autoSaveDefValue) {
        autoSaveDefValue(key, defValue, autoSaveDefValue);
        return spUtils.getFloat(key, defValue);
    }

    @Override
    public boolean getBoolean(String key, boolean defValue, boolean autoSaveDefValue) {
        autoSaveDefValue(key, defValue, autoSaveDefValue);
        return spUtils.getBoolean(key, defValue);
    }

    @Override
    public String getString(String key, String defValue, boolean autoSaveDefValue) {
        autoSaveDefValue(key, defValue, autoSaveDefValue);
        return spUtils.getString(key, defValue);
    }

    @Override
    public Object getValue(String key, Object defValue, boolean autoSaveDefValue) {
        autoSaveDefValue(key, defValue, autoSaveDefValue);
        return spUtils.getString(key);
    }

    protected void autoSaveDefValue(String key, Object defValue, boolean autoSaveDefValue) {
        if (!spUtils.contains(key)) {
            if (autoSaveDefValue) {
                putValue(key, defValue);
            }
        }
    }

    public DbSp putValue(String key, Object value) {
        DataPersistence.checkValueType(value);
        if (value == null) {
            spUtils.put(key, (String) null);
            return this;
        }
        if (value instanceof Integer) {
            spUtils.put(key, (int) value);
        } else if (value instanceof Long) {
            spUtils.put(key, (long) value);
        } else if (value instanceof Boolean) {
            spUtils.put(key, (boolean) value);
        } else if (value instanceof Float) {
            spUtils.put(key, (float) value);
        } else if (value instanceof String) {
            spUtils.put(key, (String) value);
        } else if (value instanceof Set) {
            Set<String> valueSet = (Set<String>) value;
            spUtils.put(key, valueSet);
        } else {
            throw new RuntimeException("不允许的类型");
        }
        return this;
    }

}
